<template>
  <div>
    <h1>拼团活动列表</h1>
    <!-- 搜索 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="活动名称">
          <el-input
            v-model="searchForm.activeName"
            placeholder="请输入活动名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="toAddActive">添加</el-button>
      <el-button type="danger" @click="todeleteAll">批量删除</el-button>
    </div>
    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="activeId" label="ID" />
        <el-table-column prop="activeName" label="活动名称" />
        <el-table-column prop="groupNum" label="组团人数" />
        <el-table-column prop="beginTime" label="开始时间" />
        <el-table-column prop="endTime" label="截止时间" />
        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <el-button
              type="success"
              :icon="Edit"
              circle
              @click="toUpdateActive(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              :icon="Delete"
              circle
              @click="toDeleteActive(scope.row)"
            ></el-button>
            <el-button type="warning" round @click="toAddActiveJoin(scope.row)"
              >参与</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 20px">
      <div class="demo-pagination-block" style="width: 800px; margin: 0 auto">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加 修改 弹框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title" width="500">
        <el-form :model="form">
          <el-form-item label="活动名称" :label-width="formLabelWidth">
            <el-input
              v-model="form.activeName"
              autocomplete="off"
              placeholder="请输入活动名称"
            />
          </el-form-item>
          <el-form-item label="组团人数" :label-width="formLabelWidth">
            <el-input-number v-model="form.groupNum" :min="1" />
          </el-form-item>
          <el-form-item label="开始时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.beginTime"
              type="datetime"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="截止时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="请选择截止时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              v-if="title == '添加拼团活动'"
              @click="submitAddActive()"
            >
              确定
            </el-button>
            <el-button
              type="primary"
              v-if="title == '修改拼团活动'"
              @click="onupdateActive()"
            >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 参与 -->
    <div>
      <el-dialog v-model="joinFormVisible" title="商家参与活动" width="500">
        <el-form :model="joinForm">
          <el-form-item label="拼团活动名称" :label-width="formLabelWidth">
            <el-input
              v-model="joinForm.joinName"
              autocomplete="off"
              placeholder="请输入拼团活动名称"
            />
          </el-form-item>
          <el-form-item label="拼团活动简介" :label-width="formLabelWidth">
            <el-input
              v-model="joinForm.joinDesc"
              autocomplete="off"
              placeholder="请输入拼团活动简介"
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="拼团商品" :label-width="formLabelWidth">
            <el-select
              v-model="joinForm.prodInfoId"
              placeholder="请选择拼团商品"
              clearable
            >
              <el-option
                v-for="item in prodList"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品单位" :label-width="formLabelWidth">
            <el-select
              v-model="joinForm.prodUnit"
              placeholder="请选择商品单位"
              clearable
            >
              <el-option
                v-for="item in unitList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品轮播图" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:10010/goods/index/uploadFile"
              :headers="headers"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>

          <el-form-item label="活动开始时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="joinForm.beginTime"
              type="datetime"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="活动截止时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="joinForm.endTime"
              type="datetime"
              placeholder="请选择截止时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="拼团时效(小时)" :label-width="formLabelWidth">
            <el-input-number v-model="joinForm.expireTime" :min="1" />
          </el-form-item>
          <el-form-item label="拼团人数" :label-width="formLabelWidth">
            <el-input-number v-model="joinForm.groupNum" :min="1" />
          </el-form-item>
          <el-form-item label="购买数量限制" :label-width="formLabelWidth">
            <el-input-number v-model="joinForm.buyMax" :min="1" />
          </el-form-item>
          <el-form-item label="补齐人数" :label-width="formLabelWidth">
            <el-input-number v-model="joinForm.virtualNum" :min="1" />
          </el-form-item>
          <el-form-item label="排序" :label-width="formLabelWidth">
            <el-input-number v-model="joinForm.joinTop" :min="1" />
          </el-form-item>
          <el-form-item label="配送方式" :label-width="formLabelWidth">
            <el-select
              v-model="joinForm.sendKind"
              placeholder="请选择配送方式"
              clearable
            >
              <el-option
                v-for="item in kindList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="运费设置" :label-width="formLabelWidth">
            <el-select
              v-model="joinForm.sendPay"
              placeholder="请选择运费设置"
              clearable
            >
              <el-option
                v-for="item in payList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="运费" :label-width="formLabelWidth">
            <el-input
              v-model="joinForm.sendMoney"
              autocomplete="off"
              placeholder="请输入运费"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="joinFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddActiveJoin()">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getActiveList,
  addActive,
  updateActive,
  deleteAllActive,
  deleteActive,
  getProdInfoList,
  addGroupJoin,
  getDictList,
} from "@/api/api";
import { useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import type { TableInstance } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps, UploadUserFile } from "element-plus";

import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from "@element-plus/icons-vue";
const multipleSelection = ref<any[]>([]);

const dialogFormVisible = ref(false);
const joinFormVisible = ref(false);
const formLabelWidth = "140px";
const unitList = ref([]);
const prodList = ref([]);
const kindList = ref([]);
const payList = ref([]);
const form = ref({
  activeName: null,
  beginTime: null,
  endTime: null,
  groupNum: 1,
});
const joinForm = ref({
  activeName: null,
  beginTime: null,
  buyMax: 1,
  createBy: null,
  createTime: null,
  endTime: null,
  expireTime: 1,
  groupNum: 1,
  joinDesc: null,
  joinId: null,
  joinImages: null,
  joinName: null,
  joinTop: 1,
  kindName: null,
  payName: null,
  prodInfoId: null,
  prodName: null,
  imageList: [],
  prodUnit: null,
  sendKind: null,
  sendMoney: null,
  sendPay: null,
  unitName: null,
  updateBy: null,
  updateTime: null,
  virtualNum: 1,
});

const router = useRouter();
const tableData = ref([]);
const total = ref(0);
const title = ref("");

const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  activeName: null,
});
const headers = ref({
  token: sessionStorage.getItem("token"),
});
//参与活动
const toAddActiveJoin = (row: any) => {
  joinForm.value.activeId = row.activeId;
  joinForm.value = {
    activeName: null,
    beginTime: null,
    buyMax: 1,
    createBy: null,
    createTime: null,
    endTime: null,
    expireTime: 1,
    groupNum: 1,
    imageList: [],
    joinDesc: null,
    joinId: null,
    joinImages: null,
    joinName: null,
    joinTop: 1,
    kindName: null,
    payName: null,
    prodInfoId: null,
    prodName: null,
    prodUnit: null,
    sendKind: null,
    sendMoney: null,
    sendPay: null,
    unitName: null,
    updateBy: null,
    updateTime: null,
    virtualNum: 1,
  };
  form.value.joinImages = "";
  joinFormVisible.value = true;
};

//多选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
//多图
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//提交参与活动表单
const submitAddActiveJoin = () => {
  if (fileList.value.length > 0) {
    const images = [];
    fileList.value.forEach((item) => {
      images.push(item.response.data);
    });
    form.value.joinImages = JSON.stringify(images);
  }
  addGroupJoin(joinForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      joinFormVisible.value = false;

      router.push("/home/team");
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//批量删除活动
const todeleteAll = () => {
  ElMessageBox.confirm("数据删除后无法恢复,您确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAllActive(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};

//删除活动 单删
const toDeleteActive = (row: any) => {
  ElMessageBox.confirm("数据删除后无法恢复,您确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteActive(row).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};

//添加活动
const submitAddActive = () => {
  addActive(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
//修改活动
const onupdateActive = () => {
  updateActive(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//打开添加表单
const toAddActive = () => {
  title.value = "添加拼团活动";
  form.value = {
    activeName: null,
    beginTime: null,
    endTime: null,
    groupNum: 1,
  };
  dialogFormVisible.value = true;
};
//修改活动
const toUpdateActive = (row: any) => {
  title.value = "修改拼团活动";
  Object.assign(form.value, row);
  dialogFormVisible.value = true;
};

//分页回调
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};
const loadList = () => {
  getActiveList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadList();
  //获取商品单位
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  //获取配送方式
  getDictList(16).then((res) => {
    if (res.data.code == 200) {
      kindList.value = res.data.data;
    }
  });
  //获取运费方式
  getDictList(17).then((res) => {
    if (res.data.code == 200) {
      payList.value = res.data.data;
    }
  });
  //获取商品
  getProdInfoList().then((res) => {
    if (res.data.code == 200) {
      prodList.value = res.data.data;
    }
  });
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
